package com.chinawayltd.ews.sample.service.basicInfo.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections4.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.chinawayltd.ews.sample.core.exception.BusinessException;
import com.chinawayltd.ews.sample.mapper.TBranchConsumeTimeMapper;
import com.chinawayltd.ews.sample.mapper.TBranchMapper;
import com.chinawayltd.ews.sample.mapper.TLogMapper;
import com.chinawayltd.ews.sample.mapper.basicInfo.BranchConsumeTimeExtendMapper;
import com.chinawayltd.ews.sample.model.TBranch;
import com.chinawayltd.ews.sample.model.TBranchConsumeTime;
import com.chinawayltd.ews.sample.model.TBranchConsumeTimeExample;
import com.chinawayltd.ews.sample.model.TBranchExample;
import com.chinawayltd.ews.sample.model.TBranchExample.Criteria;
import com.chinawayltd.ews.sample.model.TLog;
import com.chinawayltd.ews.sample.model.basicInfo.BranchConsumeTimeVO;
import com.chinawayltd.ews.sample.service.base.impl.BaseServiceImpl;
import com.chinawayltd.ews.sample.service.basicInfo.BranchConsumeTimeService;
import com.chinawayltd.ews.sample.util.PageData;
import com.chinawayltd.ews.sample.util.StringUtils;
import com.chinawayltd.ews.sample.util.excel.ExcelObjModel;
import com.chinawayltd.ews.sample.util.excel.ExportCloumsModel;
import com.chinawayltd.ews.sample.web.query.BranchConsumeTimeGirdQuery;

/**
 * @program: greeProject
 * @description 实现类
 * @author: chenxin
 * @create: 2018年4月11日 下午10:52:48
 */
@Service
public class BranchConsumeTimeServiceImpl extends BaseServiceImpl implements BranchConsumeTimeService {

	@Autowired
	TBranchConsumeTimeMapper tBranchConsumeTimeMapper;
	@Autowired
	BranchConsumeTimeExtendMapper branchConsumeTimeExtendMapper;
	@Autowired
	TBranchMapper tBranchMapper;
	@Autowired
	private TLogMapper tLogMapper;
	
	private final String tableName = "T_BRANCH_CONSUME_TIME";

	@Override
	public List<BranchConsumeTimeVO> list(BranchConsumeTimeGirdQuery queryParam) {
		return branchConsumeTimeExtendMapper.list(queryParam);
	}

	@Override
	public TBranchConsumeTime getById(Long id) throws Exception{
		if(id == null || id <= 0){
            throw new RuntimeException("id不能为空或者少于等于0！");
        }
		return tBranchConsumeTimeMapper.selectByPrimaryKey(id);
	}

	@Override
	@Transactional
	public int add(TBranchConsumeTime tBranchConsumeTime) throws Exception{
		Date date = new Date();
		tBranchConsumeTime.setCreateTime(date);
		tBranchConsumeTime.setUpdateTime(date);
		if(StringUtils.isBlank(tBranchConsumeTime.getStartBranch().toString()) || StringUtils.isBlank(tBranchConsumeTime.getArniveBranch().toString())){
			throw new BusinessException("数据空值，添加失败!");
		}
		if(tBranchConsumeTime.getStartBranch().equals(tBranchConsumeTime.getArniveBranch())){
			throw new BusinessException("出发站点不能与到达站点相同!");
		}
		Byte vehicleModels_ = tBranchConsumeTime.getVehicleModels();
		if(vehicleModels_ == null){
			throw new BusinessException("车型（板）不能为空!");
		}
		//判断车型（板）是否重复
		TBranchConsumeTime tc = this.selectByTBranchConsumeTime(tBranchConsumeTime);
		if(tc !=null){
			throw new BusinessException("该出发站点和到达站点下已存在该车型，添加失败!");
		}
				
		int result = branchConsumeTimeExtendMapper.insert(tBranchConsumeTime);
		if (result > 0) {
			TLog log = new TLog();
			log.setDataId(tBranchConsumeTime.getId());
			log.setTableName(tableName);
			log.setOperationUser(getCurrentUser().getRealname());
			log.setOperationType(1);
			log.setCreateTime(date);
			log.setUpdateTime(date);
			tLogMapper.insert(log);
		}
		return result;
	}

	@Override
	@Transactional
	public int update(TBranchConsumeTime tBranchConsumeTime) throws Exception{
		Date date = new Date();
		TBranchConsumeTime data = tBranchConsumeTimeMapper.selectByPrimaryKey(tBranchConsumeTime.getId());
		data.setUpdateTime(date);
		if(StringUtils.isBlank(tBranchConsumeTime.getId().toString())){
			throw new BusinessException("数据空值，修改失败!");
		}
		if(StringUtils.isBlank(tBranchConsumeTime.getStartBranch().toString()) || StringUtils.isBlank(tBranchConsumeTime.getArniveBranch().toString())){
			throw new BusinessException("数据空值，修改失败!");
		}
		if(tBranchConsumeTime.getStartBranch().equals(tBranchConsumeTime.getArniveBranch())){
			throw new BusinessException("出发站点不能与到达站点相同!");
		}
		//判断车型（板）是否重复
		TBranchConsumeTime tc = this.selectByTBranchConsumeTime(tBranchConsumeTime);
		if(tc !=null){
			throw new BusinessException("该出发站点和到达站点下已存在该车型，添加失败!");
		}
		data.setStartBranch(tBranchConsumeTime.getStartBranch());
		data.setArniveBranch(tBranchConsumeTime.getArniveBranch());
		data.setVehicleModels(tBranchConsumeTime.getVehicleModels());
		data.setTravelTime(tBranchConsumeTime.getTravelTime());
		int result = tBranchConsumeTimeMapper.updateByPrimaryKeySelective(data);
		if (result > 0) {
			TLog log = new TLog();
			log.setDataId(tBranchConsumeTime.getId());
			log.setTableName(tableName);
			log.setOperationUser(getCurrentUser().getRealname());
			log.setOperationType(2);
			log.setCreateTime(date);
			log.setUpdateTime(date);
			tLogMapper.insert(log);
		}
		return result;
	}

	@Override
	public int delete(Long id) throws Exception {
		if(id == null || id <= 0){
            throw new RuntimeException("id不能为空或者少于等于0！");
        }
		return tBranchConsumeTimeMapper.deleteByPrimaryKey(id);
	}

	@Override
	@Transactional
	public int deletesByIds(String ids) throws Exception {
		if(StringUtils.isBlank(ids)){
            throw new RuntimeException("数据不能为空！");
        }
		String[] idArr = ids.split(",");
		return branchConsumeTimeExtendMapper.deleteAll(idArr);
	}

	@Override
	@Transactional
	public ExcelObjModel insertList(List<PageData> list) {
		ExcelObjModel model = new ExcelObjModel();
		List<Object> mapList = new ArrayList<>();
		model.setCode(0); // 0没添加1添加成功，否则有添加不成功的
		int result = 0;
		Date now = new Date();
		String abnormalStr = null;//标识异常列
		//遍历读取的Excel数据，判断数据的正确性
		for (PageData pd : list) {
			try {
				BranchConsumeTimeVO tBranchConsumeTime = new BranchConsumeTimeVO();
				//出发站点id
				String startBranch = pd.getString("var0");
				tBranchConsumeTime.setStartBranchName(startBranch);
				//到达站点id
				String arniveBranch = pd.getString("var1");
				tBranchConsumeTime.setArniveBranchName(arniveBranch);
				//车型（板位）
				abnormalStr = "C";
				String vehicleModels = pd.getString("var2");
				if(StringUtils.isNoneBlank(vehicleModels)){
					tBranchConsumeTime.setVehicleModels((byte)Integer.valueOf(vehicleModels).intValue());
				}
				//行程耗时
				abnormalStr = "D";
				String travelTime = pd.getString("var3");
				if(StringUtils.isNoneBlank(travelTime)){
					tBranchConsumeTime.setTravelTime((short)Integer.valueOf(travelTime).intValue());
				}
				//将对象转化为map，判断是否为空
				Map<String, Object> map = com.chinawayltd.ews.sample.util.MapUtils.objectToMap(tBranchConsumeTime);
				if(StringUtils.isBlank(startBranch) || StringUtils.isBlank(arniveBranch) || StringUtils.isBlank(vehicleModels) || StringUtils.isBlank(travelTime)){
					map.put("describe", "填写的字段不能为空");
					map.put("travelTime", travelTime);
					map.put("vehicleModels", vehicleModels);
					mapList.add(map);
					continue;
				}
				
				//查询站点名称是否存在
				Map<String, Object> flag = this.judgeBranchNameExist(startBranch);
				if(MapUtils.getInteger(flag, "flag") > 0){
					//如果存在，则可以开始存入
					tBranchConsumeTime.setStartBranch(MapUtils.getLong(flag, "id"));
				}else {
					//如果不存在，则记录错误
					map.put("describe", "第A列：出发站点“" + startBranch + "”不存在");
					map.put("travelTime", travelTime);
					map.put("vehicleModels", vehicleModels);
					mapList.add(map);
					continue;
				}
				Map<String, Object> flag1 = this.judgeBranchNameExist(arniveBranch);
				if(MapUtils.getInteger(flag1, "flag") > 0){
					//如果存在，则可以开始存入
					tBranchConsumeTime.setArniveBranch(MapUtils.getLong(flag1, "id"));
				}else {
					//如果不存在，则记录错误
					map.put("describe", "第B列：到达站点“" + arniveBranch + "”不存在");
					map.put("travelTime", travelTime);
					map.put("vehicleModels", vehicleModels);
					mapList.add(map);
					continue;
				}
				if(tBranchConsumeTime.getTravelTime() <0){
					//如果不存在，则记录错误
					map.put("describe", "第D列：耗时时长不能小于0");
					map.put("travelTime", travelTime);
					map.put("vehicleModels", vehicleModels);
					mapList.add(map);
					continue;
				}
				if(tBranchConsumeTime.getVehicleModels() <0){
					//如果不存在，则记录错误
					map.put("describe", "第C列：车板位数应为16或20或30");
					map.put("travelTime", travelTime);
					map.put("vehicleModels", vehicleModels);
					mapList.add(map);
					continue;
				}
				Byte bytes = tBranchConsumeTime.getVehicleModels();
				if(bytes !=16 && bytes !=20 && bytes !=30){
					map.put("describe", "第C列：车板位数应为16或20或30");
					map.put("travelTime", travelTime);
					map.put("vehicleModels", vehicleModels);
					mapList.add(map);
					continue;
				}
				if(tBranchConsumeTime.getStartBranch().equals(tBranchConsumeTime.getArniveBranch())){
					map.put("describe", "第A和第B列：出发站点不能与到达站点相同,导入失败!");
					map.put("travelTime", travelTime);
					map.put("vehicleModels", vehicleModels);
					mapList.add(map);
					continue;
				}
				tBranchConsumeTime.setCreateTime(now);
				tBranchConsumeTime.setUpdateTime(now);
				// TODO 插入，如果重复则更新
				Map<String, Object> resultmap = this.toLeadData(tBranchConsumeTime);
				if(MapUtils.getInteger(resultmap, "result") > 0){
					map.put("describe", MapUtils.getString(resultmap, "describe"));
					map.put("travelTime", travelTime);
					map.put("vehicleModels", vehicleModels);
					mapList.add(map);
					result = 1;
				}else{
					map.put("describe", "导入异常");
					map.put("travelTime", travelTime);
					map.put("vehicleModels", vehicleModels);
					mapList.add(map);
					continue;
				}
				
				model.setCode(result);
			} catch (Exception e) {
				e.printStackTrace();
				model.setCode(0);
				Map<String, Object> exceptionMap = new HashMap<>();
				exceptionMap.put("startBranchName", pd.getString("var0"));
				exceptionMap.put("arniveBranchName", pd.getString("var1"));
				exceptionMap.put("vehicleModels", pd.getString("var2"));
				exceptionMap.put("travelTime", pd.getString("var3"));
				exceptionMap.put("describe", "第"+abnormalStr+"列：数据异常，导入失败!");
				mapList.add(exceptionMap);
			}
			
		}
		model.setList(mapList);
		List<ExportCloumsModel> cloums = new ArrayList<>();
		if(mapList.size() > 0){
			cloums.add(new ExportCloumsModel("出发站点", "startBranchName"));
			cloums.add(new ExportCloumsModel("结束站点", "arniveBranchName"));
			cloums.add(new ExportCloumsModel("车型（板）", "vehicleModels"));
			cloums.add(new ExportCloumsModel("耗时时长（分钟）", "travelTime"));
			cloums.add(new ExportCloumsModel("导入描述", "describe"));
		}
		model.setCloums(cloums);
		return model;
	}

	/**
	 * 导入数据
	 * @author Fay
	 * @date 2018年5月7日 下午2:18:03
	 * @param tBranchConsumeTime
	 * @return
	 */
	@Transactional
	private Map<String, Object> toLeadData(BranchConsumeTimeVO tBranchConsumeTime) {
		TLog log = new TLog();
		Map<String, Object> resultMap = new HashMap<>();
		TBranchConsumeTimeExample example = new TBranchConsumeTimeExample();
		com.chinawayltd.ews.sample.model.TBranchConsumeTimeExample.Criteria createCriteria = example.createCriteria();
		createCriteria.andStartBranchEqualTo(tBranchConsumeTime.getStartBranch());
		createCriteria.andArniveBranchEqualTo(tBranchConsumeTime.getArniveBranch());
		createCriteria.andVehicleModelsEqualTo(tBranchConsumeTime.getVehicleModels());
		List<TBranchConsumeTime> selectByExample = tBranchConsumeTimeMapper.selectByExample(example);
		
		int result = 0;
		// 存在则更新
		if(selectByExample.size() > 0){
			tBranchConsumeTime.setId(selectByExample.get(0).getId());// 正常来说只有一条，不能有重复
			result = tBranchConsumeTimeMapper.updateByPrimaryKey(tBranchConsumeTime);
			resultMap.put("describe", "已更新");
			log.setOperationType(2);
		}else{
			result = branchConsumeTimeExtendMapper.insertExtendVo(tBranchConsumeTime);
			log.setOperationType(1);
			resultMap.put("describe", "导入成功");
		}
		
		if(result > 0){
    		log.setDataId(tBranchConsumeTime.getId());
    		log.setTableName(tableName);
    		log.setOperationUser(getCurrentUser().getRealname());
    		log.setCreateTime(new Date());
    		log.setUpdateTime(new Date());
    		tLogMapper.insert(log);
		}
		resultMap.put("result", result);
		return resultMap;
	}

	/**
	 * 判断站点名称是否存在
	 * @author Fay
	 * @date 2018年5月2日 下午4:20:00
	 * @param branchName
	 * @return
	 */
	private Map<String, Object> judgeBranchNameExist(String branchName){
		Map<String, Object> resultModel = new HashMap<>();
		
		TBranchExample branchNameExample = new TBranchExample();
		Criteria branchNameCriteria = branchNameExample.createCriteria();
		branchNameCriteria.andBranchNameEqualTo(branchName);
		List<TBranch> tBranchList = tBranchMapper.selectByExample(branchNameExample);
		if(tBranchList.size() > 0){
			//如果存在
			//如果获取的数据List只有一条证明只有一条站点信息，如果有多条证明有重复的数据，那也就只拿第一条数据
			Long branchId = tBranchList.get(0).getId();
			resultModel.put("id", branchId);
			resultModel.put("flag", 1);
			return resultModel;
		}else {
			//如果不存在
			resultModel.put("flag", 0);
			return resultModel;
		}
	}

	@Override
	public boolean judgeVehicleModelExist(TBranchConsumeTime tBranchConsumeTime) {
		Long id_ = tBranchConsumeTime.getId();
		Byte vehicleModels_ = tBranchConsumeTime.getVehicleModels();
		TBranchConsumeTimeExample example = new TBranchConsumeTimeExample();
		example.createCriteria().andStartBranchEqualTo(tBranchConsumeTime.getStartBranch()).andArniveBranchEqualTo(tBranchConsumeTime.getArniveBranch()).andVehicleModelsEqualTo(tBranchConsumeTime.getVehicleModels());
		List<TBranchConsumeTime> result = tBranchConsumeTimeMapper.selectByExample(example);
		if(result != null && result.size() > 0){
			for(TBranchConsumeTime tb : result){
				Byte vehicleModels = tb.getVehicleModels();
				if(vehicleModels_ == vehicleModels){
					if(id_ != null && id_ == tb.getId()){
						return false;
					}
					return true;
				}
			}
		}
		return false;
	}

	@Override
	public TBranchConsumeTime selectByTBranchConsumeTime(TBranchConsumeTime tBranchConsumeTime) {
		// TODO Auto-generated method stub
		return branchConsumeTimeExtendMapper.selectByTBranchConsumeTime(tBranchConsumeTime);
	}
}
